package com.shaobufan.museum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shaobufan.museum.mapper.UserMapper;
import com.shaobufan.museum.pojo.entity.User;
import com.shaobufan.museum.pojo.vo.UserVo;
import com.shaobufan.museum.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;

/**
 * @author 17126
 * &#064;description  针对表【user(用户表)】的数据库操作Service实现
 * &#064;createDate  2024-03-11 18:06:46
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    private static final String SALT = "shaobufan";
    @Resource
    UserMapper userMapper;

    /**
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @return 用户
     */
    @Override
    public UserVo userLogin(String userAccount, String userPassword) {

        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("user_password", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        return getUserVo(user);
    }

    /**
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @return 用户
     */
    @Override
    public Integer userRegister(String userAccount, String userPassword, String userEmail) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        User checkUser = userMapper.selectOne(queryWrapper);
        if (checkUser != null) {
            return null;
        }

        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserEmail(userEmail);
        userMapper.insert(user);
        return user.getUserId();
    }

    /**
     * @param user 用户实体
     * @return 用户实体Vo
     */
    @Override
    public UserVo getUserVo(User user) {
        if (user == null) {
            return null;
        }
        UserVo userVo = new UserVo();
        userVo.setUserId(user.getUserId());
        userVo.setUserAccount(user.getUserAccount());
        return userVo;
    }
}